import React, { useEffect, useState, useContext, useRef } from "react";
import { Table, Button, Modal, Form, Input, message } from "antd";
import axios from "axios";
import { DeleteOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
const { confirm } = Modal;

export default function NewsCategory() {
  const [dataSource, setdataSource] = useState([]);
  useEffect(() => {
    axios.get("/categories").then(({ data }) => {
      setdataSource(data);
    });
  }, []);
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render: id => <b>{id}</b>
    },
    {
      title: "栏目名称",
      dataIndex: "title",
      //editable: true,
      onCell: record => ({
        record,
        editable: true,
        dataIndex: "title",
        title: "栏目名称",
        handleSave: item => {
          const { id, title, value } = item;
          setdataSource(
            dataSource.map(v => {
              if (v.id === id) {
                v.title = title;
                v.value = value;
              }
              return v;
            })
          );
          axios.patch(`/categories/${id}`, { title, value }).then(() => {
            message.success("栏目名称修改成功！");
          });
        }
      })
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            <Button
              danger
              icon={<DeleteOutlined />}
              shape="circle"
              size="large"
              style={{ marginRight: "10px" }}
              onClick={() => showDelConfirm(item)}
            />
          </div>
        );
      }
    }
  ];
  function showDelConfirm(item) {
    confirm({
      title: "您确定删除该分类吗?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        setdataSource(dataSource.filter(row => row.id !== item.id));
        axios.delete(`/categories/${item.id}`);
      },
      onCancel() {}
    });
  }
  const EditableContext = React.createContext(null);
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);

    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex]
      });
    };

    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log("Save failed:", errInfo);
      }
    };

    let childNode = children;

    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`
            }
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };
  return (
    <Table
      components={{
        body: {
          row: EditableRow,
          cell: EditableCell
        }
      }}
      dataSource={dataSource}
      columns={columns}
      pagination={{ pageSize: 5 }}
      rowKey={item => item.id}
    />
  );
}
